<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <!-- 搜索区域 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="用户名">
                <a-input v-model="queryParam.username" placeholder="请输入用户名"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="手机号">
                <a-input v-model="queryParam.phone" placeholder="请输入手机号"/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="性别">
                  <a-select v-model="queryParam.gender" placeholder="请选择">
                    <a-select-option value="">全部</a-select-option>
                    <a-select-option value="1">男</a-select-option>
                    <a-select-option value="2">女</a-select-option>
                    <a-select-option value="0">未知</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="注册时间">
                  <a-range-picker v-model="queryParam.createdAt" style="width: 100%" />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="状态">
                  <a-select v-model="queryParam.isDeleted" placeholder="请选择">
                    <a-select-option value="">全部</a-select-option>
                    <a-select-option value="0">正常</a-select-option>
                    <a-select-option value="1">已禁用</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => this.queryParam = {}">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!-- 操作按钮区域 -->
      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd">新增用户</a-button>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <a-menu slot="overlay">
            <a-menu-item key="1" @click="handleBatchEnable"><a-icon type="check-circle" />批量启用</a-menu-item>
            <a-menu-item key="2" @click="handleBatchDisable"><a-icon type="stop" />批量禁用</a-menu-item>
            <a-menu-item key="3" @click="handleBatchDelete"><a-icon type="delete" />批量删除</a-menu-item>
          </a-menu>
          <a-button style="margin-left: 8px">
            批量操作 <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </div>

      <!-- 表格区域 -->
      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        :alert="true"
        :rowSelection="rowSelection"
        showPagination="auto"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="avatar" slot-scope="text">
          <a-avatar :src="text || 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png'" />
        </span>
        <span slot="gender" slot-scope="text">
          <span v-if="text === 1">男</span>
          <span v-else-if="text === 2">女</span>
          <span v-else>未知</span>
        </span>
        <span slot="status" slot-scope="text">
          <a-badge :status="text === 0 ? 'success' : 'error'" :text="text === 0 ? '正常' : '已禁用'" />
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="handleResetPassword(record)">重置密码</a>
            <a-divider type="vertical" />
            <a-dropdown>
              <a class="ant-dropdown-link">
                更多 <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item v-if="record.isDeleted === 1" @click="handleEnable(record)">
                  <a-icon type="check-circle" />启用
                </a-menu-item>
                <a-menu-item v-else @click="handleDisable(record)">
                  <a-icon type="stop" />禁用
                </a-menu-item>
                <a-menu-item @click="handleDelete(record)">
                  <a-icon type="delete" />删除
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </span>
      </s-table>

      <!-- 用户表单弹窗 -->
      <a-modal
        :title="modalTitle"
        :width="640"
        :visible="visible"
        :confirmLoading="confirmLoading"
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <a-form :form="form" v-bind="formLayout">
          <a-form-item label="用户名">
            <a-input
              v-decorator="[
                'username',
                {
                  rules: [{ required: true, message: '请输入用户名' }],
                  initialValue: currentUser.username
                }
              ]"
              :disabled="currentUser.id !== undefined"
              placeholder="请输入用户名"
            />
          </a-form-item>
          <a-form-item label="昵称">
            <a-input
              v-decorator="[
                'nickname',
                {
                  rules: [{ required: true, message: '请输入昵称' }],
                  initialValue: currentUser.nickname
                }
              ]"
              placeholder="请输入昵称"
            />
          </a-form-item>
          <a-form-item v-if="!currentUser.id" label="密码">
            <a-input-password
              v-decorator="[
                'password',
                {
                  rules: [
                    { required: true, message: '请输入密码' },
                    { min: 6, message: '密码长度不能少于6位' }
                  ]
                }
              ]"
              placeholder="请输入密码"
            />
          </a-form-item>
          <a-form-item label="手机号">
            <a-input
              v-decorator="[
                'phone',
                {
                  rules: [
                    { required: true, message: '请输入手机号' },
                    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
                  ],
                  initialValue: currentUser.phone
                }
              ]"
              placeholder="请输入手机号"
            />
          </a-form-item>
          <a-form-item label="性别">
            <a-radio-group
              v-decorator="[
                'gender',
                {
                  initialValue: currentUser.gender !== undefined ? currentUser.gender : 0
                }
              ]"
            >
              <a-radio :value="1">男</a-radio>
              <a-radio :value="2">女</a-radio>
              <a-radio :value="0">未知</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="头像">
            <a-upload
              name="avatar"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :action="uploadUrl"
              :before-upload="beforeUpload"
              @change="handleAvatarChange"
            >
              <img v-if="avatarUrl" :src="avatarUrl" alt="avatar" style="width: 100%" />
              <div v-else>
                <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">上传</div>
              </div>
            </a-upload>
          </a-form-item>
          <a-form-item label="账户余额">
            <a-input-number
              v-decorator="[
                'user_account',
                {
                  initialValue: currentUser.user_account || 0
                }
              ]"
              :min="0"
              :step="10"
              style="width: 100%"
              placeholder="请输入账户余额"
            />
          </a-form-item>
        </a-form>
      </a-modal>

      <!-- 重置密码弹窗 -->
      <a-modal
        title="重置密码"
        :visible="resetPwdVisible"
        :confirmLoading="resetPwdLoading"
        @ok="handleResetPwdOk"
        @cancel="handleResetPwdCancel"
      >
        <a-form :form="resetPwdForm">
          <a-form-item label="新密码">
            <a-input-password
              v-decorator="[
                'newPassword',
                {
                  rules: [
                    { required: true, message: '请输入新密码' },
                    { min: 6, message: '密码长度不能少于6位' }
                  ]
                }
              ]"
              placeholder="请输入新密码"
            />
          </a-form-item>
          <a-form-item label="确认密码">
            <a-input-password
              v-decorator="[
                'confirmPassword',
                {
                  rules: [
                    { required: true, message: '请确认新密码' },
                    { validator: this.validateConfirmPassword }
                  ]
                }
              ]"
              placeholder="请确认新密码"
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable } from '@/components'
import moment from 'moment'

export default {
  name: 'UserManage',
  components: {
    STable
  },
  data () {
    return {
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表格列定义
      columns: [
        {
          title: '#',
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '头像',
          dataIndex: 'avatar_url',
          scopedSlots: { customRender: 'avatar' }
        },
        {
          title: '用户名',
          dataIndex: 'username'
        },
        {
          title: '昵称',
          dataIndex: 'nickname'
        },
        {
          title: '手机号',
          dataIndex: 'phone'
        },
        {
          title: '性别',
          dataIndex: 'gender',
          scopedSlots: { customRender: 'gender' }
        },
        {
          title: '账户余额',
          dataIndex: 'user_account',
          sorter: true
        },
        {
          title: '注册时间',
          dataIndex: 'created_at',
          sorter: true
        },
        {
          title: '最后更新',
          dataIndex: 'updated_at'
        },
        {
          title: '状态',
          dataIndex: 'isDeleted',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '200px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法
      loadData: parameter => {
        console.log('loadData.parameter', parameter)
        // 这里模拟后端数据，实际项目中应该调用API
        const data = {
          pageSize: parameter.pageSize,
          pageNo: parameter.pageNo,
          totalCount: 100,
          data: Array(10).fill().map((_, index) => ({
            id: index + 1,
            username: `user${index + 1}`,
            nickname: `用户${index + 1}`,
            avatar_url: index % 3 === 0 ? 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png' : '',
            phone: `1381234${String(index + 1).padStart(4, '0')}`,
            created_at: moment().subtract(Math.floor(Math.random() * 30), 'days').format('YYYY-MM-DD HH:mm:ss'),
            updated_at: moment().subtract(Math.floor(Math.random() * 10), 'days').format('YYYY-MM-DD HH:mm:ss'),
            gender: Math.floor(Math.random() * 3),
            isDeleted: Math.random() > 0.8 ? 1 : 0,
            user_account: Math.floor(Math.random() * 10000) / 100
          }))
        }
        return new Promise(resolve => {
          setTimeout(() => {
            resolve({
              pageSize: data.pageSize,
              pageNo: data.pageNo,
              totalCount: data.totalCount,
              data: data.data
            })
          }, 500)
        })
      },
      // 表单相关
      visible: false,
      confirmLoading: false,
      currentUser: {},
      form: this.$form.createForm(this),
      formLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 16 }
      },
      // 头像上传相关
      uploadUrl: '/api/upload',
      uploadLoading: false,
      avatarUrl: '',
      // 重置密码相关
      resetPwdVisible: false,
      resetPwdLoading: false,
      resetPwdForm: this.$form.createForm(this),
      resetPwdUserId: null,
      // 表格选择
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  computed: {
    modalTitle () {
      return this.currentUser.id ? '编辑用户' : '新增用户'
    },
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    // 展开/收起高级搜索
    toggleAdvanced () {
      this.advanced = !this.advanced
    },

    // 表格选择
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },

    // 新增用户
    handleAdd () {
      this.currentUser = {}
      this.avatarUrl = ''
      this.visible = true
      this.$nextTick(() => {
        this.form.resetFields()
      })
    },

    // 编辑用户
    handleEdit (record) {
      this.currentUser = { ...record }
      this.avatarUrl = record.avatar_url
      this.visible = true
      this.$nextTick(() => {
        this.form.resetFields()
      })
    },

    // 表单提交
    handleOk () {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true
          console.log('表单数据:', values)

          // 模拟API请求
          setTimeout(() => {
            this.visible = false
            this.confirmLoading = false
            this.$message.success(this.currentUser.id ? '修改成功' : '添加成功')
            this.$refs.table.refresh()
          }, 1000)
        }
      })
    },

    // 关闭表单
    handleCancel () {
      this.visible = false
    },

    // 头像上传前校验
    beforeUpload (file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('只能上传JPG/PNG格式的图片!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('图片大小不能超过2MB!')
      }
      return isJpgOrPng && isLt2M
    },

    // 头像上传状态变化
    handleAvatarChange (info) {
      if (info.file.status === 'uploading') {
        this.uploadLoading = true
        return
      }
      if (info.file.status === 'done') {
        // 获取上传后的图片URL
        this.uploadLoading = false
        this.avatarUrl = info.file.response.url
      }
    },

    // 重置密码
    handleResetPassword (record) {
      this.resetPwdUserId = record.id
      this.resetPwdVisible = true
      this.$nextTick(() => {
        this.resetPwdForm.resetFields()
      })
    },

    // 确认密码校验
    validateConfirmPassword (rule, value, callback) {
      const form = this.resetPwdForm
      if (value && value !== form.getFieldValue('newPassword')) {
        callback(new Error('两次输入的密码不一致!'))
      } else {
        callback()
      }
    },

    // 提交重置密码
    handleResetPwdOk () {
      this.resetPwdForm.validateFields((err, values) => {
        if (!err) {
          this.resetPwdLoading = true
          console.log('重置密码:', values)

          // 模拟API请求
          setTimeout(() => {
            this.resetPwdVisible = false
            this.resetPwdLoading = false
            this.$message.success('密码重置成功')
          }, 1000)
        }
      })
    },

    // 取消重置密码
    handleResetPwdCancel () {
      this.resetPwdVisible = false
    },

    // 启用用户
    handleEnable (record) {
      this.$confirm({
        title: '确认启用',
        content: `确定要启用用户 ${record.username} 吗？`,
        onOk: () => {
          // 模拟API请求
          setTimeout(() => {
            this.$message.success('启用成功')
            this.$refs.table.refresh()
          }, 500)
        }
      })
    },

    // 禁用用户
    handleDisable (record) {
      this.$confirm({
        title: '确认禁用',
        content: `确定要禁用用户 ${record.username} 吗？`,
        onOk: () => {
          // 模拟API请求
          setTimeout(() => {
            this.$message.success('禁用成功')
            this.$refs.table.refresh()
          }, 500)
        }
      })
    },

    // 删除用户
    handleDelete (record) {
      this.$confirm({
        title: '确认删除',
        content: `确定要删除用户 ${record.username} 吗？此操作不可恢复！`,
        okType: 'danger',
        onOk: () => {
          // 模拟API请求
          setTimeout(() => {
            this.$message.success('删除成功')
            this.$refs.table.refresh()
          }, 500)
        }
      })
    },

    // 批量启用
    handleBatchEnable () {
      this.$confirm({
        title: '批量启用',
        content: `确定要启用选中的 ${this.selectedRowKeys.length} 个用户吗？`,
        onOk: () => {
          // 模拟API请求
          setTimeout(() => {
            this.$message.success('批量启用成功')
            this.selectedRowKeys = []
            this.$refs.table.refresh()
          }, 500)
        }
      })
    },

    // 批量禁用
    handleBatchDisable () {
      this.$confirm({
        title: '批量禁用',
        content: `确定要禁用选中的 ${this.selectedRowKeys.length} 个用户吗？`,
        onOk: () => {
          // 模拟API请求
          setTimeout(() => {
            this.$message.success('批量禁用成功')
            this.selectedRowKeys = []
            this.$refs.table.refresh()
          }, 500)
        }
      })
    },

    // 批量删除
    handleBatchDelete () {
      this.$confirm({
        title: '批量删除',
        content: `确定要删除选中的 ${this.selectedRowKeys.length} 个用户吗？此操作不可恢复！`,
        okType: 'danger',
        onOk: () => {
          // 模拟API请求
          setTimeout(() => {
            this.$message.success('批量删除成功')
            this.selectedRowKeys = []
            this.$refs.table.refresh()
          }, 500)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}
.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
